﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Mani.Common
{
    public class UIHelper
    {

        // TODO: rename FormatString, FormatStringNonZero, RemoveFormat to include 'Money' in name

        private static string Rial = " ریال ";
        public static string FormatString(object obDigit)
        {
            if (obDigit == DBNull.Value)
                return "";

            float digit = Convert.ToSingle(obDigit);
            
            if (digit == 0)
                return "0";

            int numberOfDecimalDigits = 0;


            string strDigit = digit.ToString();
            if (strDigit.IndexOf('.') != -1)
                numberOfDecimalDigits = strDigit.Substring(strDigit.IndexOf('.') + 1).Length;

            NumberFormatInfo nfi = new CultureInfo("fa-IR", false).NumberFormat;
            nfi.NumberDecimalDigits = numberOfDecimalDigits;
            
            string FormatedDigit = digit.ToString("N", nfi);
            return FormatedDigit;
        }

        public static string FormatStringNonZero(object obDigit)
        {
            if (Convert.ToSingle(obDigit) == 0)
                return "";
            return FormatString(obDigit);
        }

        public static string RemoveFormat(string digit)
        {
            digit = digit.Replace(Rial, "");
            digit = digit.Replace(".00", ""); ;
            digit = digit.Replace(",", ""); ;
            return digit;
        }

        [Obsolete("Use ClientAlert(Page, string) instead")]
        public static void ClientAlert(string text)
        {
            HttpContext.Current.Response.Write("<script>alert( '" + text + "' );</script>");
        }

        public static void ClientAlert(Page page, string text)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "guardFailure", "alert( '" + text + "' );", true); // Type???
        }

        public static void ClientRedirect(Page page, string url)
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "redirect", "window.location = '" + url + "';", true);
        }

        public static string MinuteToPersianString(object o)
        {
            int mins;
            if (!int.TryParse(o.ToString(), out mins))
            {
                double d;
                if (!double.TryParse(o.ToString(), out d))
                    return "";
                mins = (int)d;
            }
            return TimeSpanToPersianString(new TimeSpan(0, mins, 0));
        }

        public static string TimeSpanToPersianString(TimeSpan timespan)
        {
            string output = String.Empty;

            if (timespan.Days != 0)
            {
                output = timespan.Days.ToString() + " روز ";
            }

            if (timespan.Hours != 0)
            {
                output = (output.Length > 1 ? output += "و " : output);
                output += timespan.Hours.ToString() + " ساعت ";
            }

            if (timespan.Minutes != 0)
            {
                output = (output.Length > 1 ? output += "و " : output);
                output += timespan.Minutes + " دقیقه ";
            }

            if (output.Length < 1)
                output = "کمتر از یک دقیقه";

            return output;
        }

        public static string TimeSpanToPersianStringWithoutHour(TimeSpan timespan)
        {
            string output = String.Empty;

            if (timespan.Days != 0)
            {
                output = timespan.Days.ToString() + " روز ";
            }

            if (timespan.Days < 1 && timespan.Hours != 0)
            { // HADI>> I added "timespan.Days < 1 " to shorten the otput
                output = (output.Length > 1 ? output += "و " : output);
                output += timespan.Hours.ToString() + " ساعت ";
            }

            if (output.Length < 1)
            {
                if (timespan.Minutes != 0)
                {
                    output = (output.Length > 1 ? output += "و " : output);
                    output += timespan.Minutes + " دقیقه ";
                }

                if (output.Length < 1)
                    output = "کمتر از یک دقیقه";
            }

            return output;
        }


        public static string RemovePersianDateTimeFormat(string text)
        {
            text = text.Replace("ب.ظ", "PM");
            text = text.Replace("ق.ظ", "AM");
            return text;
        }

        #region controlhelpers

        public static Control FindControl(object baseControl, string name)
        {
            Control basec = (Control)baseControl;
            if (basec.ID == name) return basec;

            foreach (Control c in basec.Controls)
            {
                Control child = FindControl(c, name);
                if (child != null)
                    return child;
            }

            return null;
        }

        public static CheckBox FindCheckBox(object baseControl, string name)
        {
            return FindControl(baseControl, name) as CheckBox;
        }

        public static DropDownList FindDropDownList(object baseControl, string name)
        {
            return FindControl(baseControl, name) as DropDownList;
        }

        public static RadioButton FindRadioButton(object baseControl, string name)
        {
            return FindControl(baseControl, name) as RadioButton;
        }

        public static void ClearChildControls(Control control)
        {
            foreach (Control c in control.Controls)
            {
                if (c.Controls != null && c.Controls.Count != 0)
                    ClearChildControls(c);

                if (c is TextBox)
                    ((TextBox)c).Text = "";
                else if (c is DropDownList)
                    ((DropDownList)c).SelectedIndex = 0;
            }
        }

        #endregion

        public static string HtmlFormatError(List<string> errors)
        {
            // Q: HtmlTextWriter
            string html = "";
            if (errors.Count != 0)
            {
                html += "<ul>";
                foreach (string s in errors)
                {
                    html += string.Format("<li>{0}</li>", s);
                }
                html += "</ul>";
            }
            return html;
        }

        ///////////////////

        public static string SetColors(string text)
        {
            text = text.Replace("Error", "<span style='background:#FF6666; color:#fff;'>Error</span>");
            text = text.Replace("Warning", "<span style='background:#FFFF66;'>Warning</span>");
            text = text.Replace("Alive", "<span style='background:#A5FD7E;'>Alive</span>");
            return text;
        }

        public static void GridDeleteConfirm(System.Web.UI.WebControls.GridViewRow row)
        {
            if (row.RowType != DataControlRowType.DataRow) return;

            LinkButton btnDelete = (LinkButton)row.Cells[row.Cells.Count - 1].Controls[0];
            if (btnDelete == null) return;

            btnDelete.OnClientClick = "javascript:var result = confirm('آیا نسبت به حذف مطمئن هستید');if(result==false) { return false };";
        }

        public static void DeleteExceptionHandler(System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs e)
        {
            if (e.Exception != null)
            {
                e.ExceptionHandled = true;
                throw new Exception("قابل حذف نمی باشد چرا که در حال استفاده می باشد");
            }
        }

    }
}